package com.leetcode.partition2;

import java.util.*;

/**
 * @author `RKC`
 * @date 2021/9/28 17:41
 */
public class LC128最长连续序列 {

    public static int longestConsecutive(int[] nums) {
        return dynamicProgramming(nums);
    }

    public static void main(String[] args) {
//        int[] nums = {100, 4, 200, 1, 3, 2};
        int[] nums = {0, 3, 7, 2, 5, 8, 4, 6, 0, 1};
//        int[] nums = {0, -1};
        System.out.println(longestConsecutive(nums));
    }

    private static int unionFind(int[] nums) {
        if (nums.length == 0) return 0;
        Map<Integer, Integer> root = new HashMap<>();
        int answer = 1;
        for (int num : nums) root.put(num, num);        //初始化，每个节点的根结点都是自己

        //进行union操作，如果num+1不存在的话是不会改变num的跟节点的
        for (int num : nums) union(root, num, num + 1);
        for (int i = 0; i < nums.length; i++) {
            answer = Math.max(answer, find(root, nums[i]) - nums[i] + 1);
        }
        return answer;
    }

    private static int find(Map<Integer, Integer> root, int x) {
        Integer rootX = root.get(x);
        if (rootX == null) return Integer.MAX_VALUE;
        if (x != rootX) return find(root, rootX);
        return x;
    }

    private static void union(Map<Integer, Integer> root, int x, int y) {
        int rootX = find(root, x), rootY = find(root, y);
        //没有有效根节点，取消union操作
        if (rootX == Integer.MAX_VALUE || rootY == Integer.MAX_VALUE) return;
        //如果x和y都有有效根节点，则将x合并到y中
        root.put(rootX, rootY);
    }

    private static int hashTable(int[] nums) {
        Set<Integer> ht = new HashSet<>();
        for (int num : nums) ht.add(num);

        int answer = 0;
        for (Integer num : ht) {
            if (!ht.contains(num - 1)) {
                int startNum = num, temp = 0;
                while (ht.contains(startNum)) {
                    startNum++;
                    temp++;
                }
                answer = Math.max(answer, temp);
            }
        }
        return answer;
    }

    private static int dynamicProgramming(int[] nums) {
        Arrays.sort(nums);
        int answer = 0;
        int[] dp = new int[nums.length];
        dp[0] = 1;
        for (int i = 1; i < dp.length; i++) {
            if (nums[i] - 1 == nums[i - 1]) {
                dp[i] = dp[i - 1] + 1;
            } else {
                dp[i] = 1;
            }
            answer = Math.max(answer, dp[i]);
        }
        System.out.println(Arrays.toString(dp));
        return answer;
    }
}
